package com.zhou.springsecurityoauth2.config;

import com.zhou.springsecurityoauth2.redisconfig.RedisCache;
import com.zhou.springsecurityoauth2.service.impl.LoginServcieImpl;
import com.zhou.springsecurityoauth2.service.impl.UserDetailsServiceImpl;
import com.zhou.springsecurityoauth2.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;

/**
 * @author zhou
 * @version 1.0
 * @date 2022/10/9 - 10 - 09 - 13:13
 * @description com.zhou.springsecurityoauth2.config
 */
@Component
@RequiredArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private final RedisCache redisCache;

    private final Environment environment;

//    private final AuthenticationEntryPoint authenticationEntryPoint;
//
//    private final AccessDeniedHandler accessDeniedHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain)
            throws ServletException, IOException {
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        String object;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            object=claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException("token解析异常");
        }

        String redisKey="login"+object;
        UserDetailsServiceImpl.LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(httpServletRequest,httpServletResponse);

    }


}
